package com.app.micaihu.view.user.userinfo.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.NonNull;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.adapter.NewsAdapter;
import com.app.micaihu.base.BaseSwipeMenuListActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.listener.BackGestureListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.CollectUtils;
import com.app.utils.swipemenulistview.SwipeMenu;
import com.app.utils.swipemenulistview.SwipeMenuCreator;
import com.app.utils.swipemenulistview.SwipeMenuItem;
import com.app.utils.swipemenulistview.SwipeMenuListView;
import com.app.utils.util.ViewSizeUtils;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Guo on 2016/8/2.
 * <p/>
 * <p/>
 * 我的收藏
 */
public class MyHomePageCollectionActicity extends BaseSwipeMenuListActivity<NewsEntity> implements SwipeMenuListView.OnSwipeListener {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("我的收藏");
        if (mSwipeMenuListView != null) {
            mSwipeMenuListView.setOnSwipeListener(this);
        }
    }

    @Override
    protected void configSwiperMenuListView() {
// step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
//                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
//                        0x3F, 0x25)));

                deleteItem.setBackground(R.color.common_bg_color_3);
                // set item width
                // set a icon
                deleteItem.setWidth(ViewSizeUtils.dp2px(MyHomePageCollectionActicity.this, 90));
                deleteItem.setIcon(R.drawable.common_delete_icon);
//                deleteItem.setTitle("删除");
//                deleteItem.setTitleSize(18);
//                deleteItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        // set creator
        mSwipeMenuListView.setMenuCreator(creator);
        // step 2. listener item click event
        mSwipeMenuListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0://删除当前点击的数据
                        deleteNews(position);

                        break;
                }
            }
        });
    }

    /**
     * 删除 收藏
     *
     * @param position
     */
    private void deleteNews(int position) {
        NewsEntity newsEntity = null;
        if (dataList != null && dataList.size() > position) {
            newsEntity = dataList.get(position);
            dataList.remove(position);
        }
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        if (dataList != null && dataList.isEmpty()) {
            setLoadView(DATAEMPTY, R.drawable.empty_icon_collect, getString(R.string.empty_collection2), getString(R.string.empty_collection));
        }
        if (newsEntity == null) {
            return;
        }

        CollectUtils.getInstance().deleteSaveNews(newsEntity.getArticleId());

    }


    /**
     * 请求数据
     *
     * @param isRefresh
     */
    @Override
    protected void changeData(final boolean isRefresh) {
        if (UserInforManager.getInstance().isLogin()) {

            Map<String, String> params = new HashMap<>();
            params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
            params.put("page", mDataPage + "");

            addPostRequest(URIContant.MY_COLLECTION, new TypeToken<DataBean<ArrayList<NewsEntity>>>() {
                    }.getType()
                    , params, new HttpListener<DataBean<ArrayList<NewsEntity>>>() {
                        @Override
                        public void onStart() {
                            super.onStart();
                            setLoadView(LOADING, null);
                        }

                        @Override
                        public void onError(VolleyError error) {

                            //拿本地的
                            loadLocalData(isRefresh);
                        }

                        @Override
                        public void onSuccess(DataBean<ArrayList<NewsEntity>> response) {
                            if (!response.noError()) {//CODE失败
                                setLoadView(DATAERROR, getResources().getString(R.string.neterror));
                                if (!isRefresh) mDataPage--;
                            } else {//code = 0
                                List<NewsEntity> collectionList = response.getData();
                                if (collectionList == null || collectionList.size() == 0) {
                                    if (dataList != null && dataList.size() > 0) {//证明是第二次请求,显示没有更多数据
                                        setLoadView(LOADSUCES, getResources().getString(R.string.nomore_collection));
                                    } else {
                                        setLoadView(DATAEMPTY, R.drawable.empty_icon_collect, getString(R.string.empty_collection2), getString(R.string.empty_collection));
                                    }
                                    if (!isRefresh) mDataPage--;
                                } else {
                                    if (dataList == null) {
                                        dataList = new ArrayList<NewsEntity>();
                                    }
                                    if (isRefresh) {
                                        dataList.clear();
                                    }
                                    //去除错误问题--->针对于articalType不匹配的问题，将其从数据中删除
                                    removeErrorData(collectionList);
                                    // 追加数据集合
                                    dataList.addAll(collectionList);

                                    if (mAdapter == null) {
                                        mAdapter = new NewsAdapter(dataList, mActivity, null);
                                        mSwipeMenuListView.setAdapter(mAdapter);
                                    } else {
                                        mAdapter.notifyDataSetChanged();
                                    }
                                    setFootView(false, null);
                                }
                            }
                        }
                    });
        } else {
            loadLocalData(isRefresh);
        }
    }

    /**
     * 去除错误数据
     *
     * @param collectionList
     */
    private void removeErrorData(@NonNull List<NewsEntity> collectionList) {

        for (int i = 0; i < collectionList.size(); i++) {
            if (TextUtils.isEmpty(TypeConstant.getNewsTypeName(collectionList.get(i).getArticleType()))) {//如果为空，则去除掉
                collectionList.remove(i);
                i--;
                continue;
            }
        }
    }

    private void loadLocalData(boolean isRefresh) {
        if (dataList == null) {
            dataList = new ArrayList<NewsEntity>();
        }
        //每次查出20条数据
        List<NewsEntity> localNewsList = CollectUtils.getInstance().getLocalNewsList(dataList.size(), 20);
        if ((localNewsList == null || localNewsList.size() == 0) && (dataList == null || dataList.size() == 0)) {
            setLoadView(DATAEMPTY, R.drawable.empty_icon_collect, getString(R.string.empty_collection2), getString(R.string.empty_collection));
            if (!isRefresh) mDataPage--;
        } else {
            if (isRefresh) {
                dataList.clear();
            }

            //加载更多,现在是datalist有数据,如果再查的有数据
            if (localNewsList != null && localNewsList.size() > 0) {
                // 追加数据集合
                dataList.addAll(localNewsList);
                if (mAdapter == null) {
                    mAdapter = new NewsAdapter(dataList, mActivity, null);
                    mSwipeMenuListView.setAdapter(mAdapter);
                } else {
                    mAdapter.notifyDataSetChanged();
                }
            }

            if ((localNewsList == null || localNewsList.size() == 0)) {//没有更多了
                setFootView(false, getResources().getString(R.string.nomore_collection));
            } else {

                setFootView(false, null);
            }


        }
    }


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {

        if (dataList == null) {
            return;
        }
        if (position >= dataList.size()) {
            position = dataList.size() - 1;
        } else if (position < 0) {
            position = 0;
        }
        NewsEntity newsEntity = dataList.get(position);
        if (newsEntity == null) {
            return;
        }
        TypeConstant.openTypeDetail(newsEntity, this, TypeConstant.SOURCETYPE_NORMAL);
    }

    @Override
    public void onSwipeStart(int position) {

    }

    @Override
    public void onSwipeEnd(int position) {

    }

    @Override
    public void onDownAction(boolean isOpen) {
    }
}
